<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Volunteer extends Model
{
    protected  $table='volunteer';

    protected $fillable = [
        'user_id',
        'org_id',
        'real_name',
        'nation',
        'sex',
        'birthday',
        'phone',
        'identifier',
        'slogan',
        'reward_time',
        'id_number',
        'province_id',
        'province_name',
        'city_id',
        'city_name',
        'county_id',
        'county_name',
        'addr',
        'family_id',
        'join_family_time',
        'score',
        'address',
        'extends',
        'stars'
    ];

//    protected  $casts = [
//        'extends'=>'array'
//    ];

    protected $appends = array('address');

    public function user() {
        return $this->belongsTo('App\User', 'user_id', 'id');
    }

    public function setAddressAttribute($value) {
        $addressId = $value['id'];
        $this->attributes['province_id'] = intval(substr($addressId, 0, 2).'0000');
        $this->attributes['province_name'] = $value['province'];
        $this->attributes['city_id'] = intval(substr($addressId, 0, 4).'00');
        $this->attributes['city_name'] = $value['city'];
        $this->attributes['county_id'] = intval(substr($addressId, 0, 6));
        $this->attributes['county_name'] = $value['district'];
        $this->attributes['addr'] = isset($value['address']) ? $value['address'] : '';
    }

    public function getAddressAttribute() {
        if (!isset($this->attributes['county_id'])) {
            return null;
        }

        return [
            'id' => $this->attributes['county_id'],
            'province' => $this->attributes['province_name'],
            'city' => $this->attributes['city_name'],
            'district' => $this->attributes['county_name'],
            'address' => $this->attributes['addr'],
        ];
    }

    public function getExtendsAttribute() {
        if (isset($this->attributes['extends'])) {
            try {
                $this->attributes['extends'] = json_decode($this->attributes['extends']);
            }catch (\Exception $e) {

            }
//            dd($this->attributes['extends']);
            return $this->attributes['extends'];
        }

        return null;
    }

    public function setExtendsAttribute($value) {
        if (!empty($value)) {
            $value = json_encode($value);
        }

        $this->attributes['extends'] = $value;
    }

    public function plusTime($time) {
        if (!$this->id) {
            return false;
        }

        $this->fill([
            'reward_time' => $this->reward_time + $time
        ]);

        return $this->save();
    }
}
